import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const actions = {
	//添加一个todo
	addTodo({commit,state},todoObj){
		if(!todoObj.title.trim()) return alert('输入不能为空!')
		//判断是否有同名的事情
		const result = state.todos.find( t => t.title === todoObj.title)
		if(result){
			alert('不可重复添加！')
		}else{
			commit('ADD_TODO',todoObj)
		}
	}
}

const mutations = {
	//添加
	ADD_TODO(state,todoObj){
		state.todos.unshift(todoObj)
	},
	//勾选或取消勾选
	CHECK_TODO(state,id){
		const todoObj = state.todos.find(t => t.id === id)
		todoObj.done = !todoObj.done
	},
	//删除
	DELETE_TODO(state,id){
		const index = state.todos.findIndex(t => t.id === id)
		state.todos.splice(index,1)
	},
	//全选
	CHECK_ALL(state,done){
		state.todos.forEach(t => t.done = done );
	},
	//清除已完成
	CLEAR_ALL_DONE(){
		state.todos = state.todos.filter(t => !t.done)
	}
}

const state = {
	todos:[
		{id:'g76tyds76d',title:'吃饭',done:true},
		{id:'9i8u9sadou',title:'睡觉',done:false},
		{id:'oi7y87h898',title:'学习',done:true}
	]
}

export default new Vuex.Store({
	actions,
	mutations,
	state
})